<template>
  <div class="order-list-container">
    <!-- 订单列表表单项 -->
    <el-card class="order-card" shadow="never">
      <el-form :inline="true" label-position="right" label-width="85px" :model="orderOptions" size="small" ref='orderOptions' class="demo-form-inline order-form">
        <el-form-item label="订单号：" prop="orderId">
          <el-input v-model="orderOptions.orderId" placeholder="请输入精准订单号" suffix-icon="xxxx"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="orderOptions.phone" placeholder="请输入11位手机号" suffix-icon="xxxx" :maxlength="11" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态：" prop="orderPayFlag">
          <el-select v-model="orderOptions.orderPayFlag" clearable placeholder="全部状态">
            <el-option label="全部状态" :value="''"></el-option>
            <el-option v-for="(value, key) in orderPayFlags" :label="value" :value="Number(key)" :key="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="油站：" class="order-options-item" prop="gasId">
          <el-select v-model="orderOptions.gasId" clearable filterable placeholder="全部油站" @change="val => gasId = val" >
            <el-option label="全部油站" :value="''">
            </el-option>
            <el-option v-for="item in gasList" :label="item.gasName"  :value="item.gasId" :key="item.gasId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="枪号：" prop="gunNo">
          <el-input  v-model="orderOptions.gunNo" placeholder="请输入数字" suffix-icon="xxxx" clearable></el-input>
        </el-form-item>
        <el-form-item label="油号：" prop="oilNo">
          <el-select v-model="orderOptions.oilNo" clearable placeholder="请选择油号">
            <el-option label="请选择油号" :value="''"></el-option>
            <el-option v-for="item in oilNumList" :label="item.oilNum" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址：">
          <address-select ref="address" v-model="address" :zoom="3" filterable></address-select>
        </el-form-item>
        <el-form-item label="下单时间：">
          <el-date-picker
            size="small"
            v-model="checkoutTime"
            :default-time="['00:00:00', '23:59:59']"
            type="datetimerange"
            unlink-panels
            align="right"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="(val) => onChangePayTime(val,'checkoutTime','orderDtStart','orderDtEnd')">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付时间：">
          <el-date-picker
            size="small"
            v-model="payTime"
            :default-time="['00:00:00', '23:59:59']"
            type="datetimerange"
            unlink-panels
            align="right"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="(val) => onChangePayTime(val,'payTime','payDtStart','payDtEnd')">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="g-flex-c">
        <el-button class="btn" style="width: 70px;" size="mini" type="primary" @click="query('check')">查询</el-button>
        <el-button style="width: 70px" size="mini" @click="resetForm" >重置</el-button>
        <el-button style="width: 70px" size="mini" @click="onExportExcel" :loading="exportLoading">导出</el-button>
      </div>
    </el-card>
    <!-- 订单列表汇总项 -->
    <el-card class="order-card"  v-loading="isAllLoading" shadow="never">
      <div class="card">
        <card title="交易总金额" width="24%" unit="元" :num="allNumber.allGunAmount | formatMoney" back='linear-gradient(225deg, #81A5FF 0%, #4B7EFE 100%)' :img="`${$ossUrl}market/effect-head.png`"/>
        <card title="实付总金额" width="24%" unit="元" :num="allNumber.allPayAmount | formatMoney" back='linear-gradient(225deg, #B7C5DC 0%, #8394B3 100%)' :img="`${$ossUrl}market/effect-money.png`" v-if="showRealAmount"/>
        <card title="订单数量" width="24%" unit="单" :num="allNumber.orderTotal | formatMoney" back='linear-gradient(225deg, #ECD39E 0%, #D6A75B 100%)' :img="`${$ossUrl}market/effect-file.png`"/>
        <card title="总升数" width="24%" unit="升" :num="allNumber.allLitre | formatMoney" back='linear-gradient(225deg, #B3B2DA 0%, #7578B4 100%)' :img="`${$ossUrl}market/effect-folder.png`"/>
      </div>
    </el-card>
    <!-- 展示退款订单数 -->
    <el-card v-if="refundNum" class="order-card none"  :body-style="{ padding: '0' }" shadow="never">
      <div class="refund-wrap">
        <img class="refund-icon" :src="`${$ossUrl}icon-notice.png`" alt="">
        <span class="refund-content">您有{{refundNum}}笔退款中的订单，请及时处理</span>
      </div>
    </el-card>
    <!-- 订单列表表格 -->
    <el-card class="order-card drawer-tabel"  :body-style="{ padding: '0' }" shadow="never">
      <el-table v-loading="loading" height="500px"  size="small" :data="orderData"  highlight-current-row stripe style="width: 100%">
        <template v-for="(item,index) in tableConfig" >
          <el-table-column v-if="item.slot === 'preferentialAmountMerchants'" :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'> 
             <template slot-scope="scope">
                <el-popover
                  placement="right"
                  width="200"
                  trigger="hover"
                  >
                  <p>商家承担直降金额: {{scope.row.activityAmountFromMt}}</p>
                  <p>商家承担平台优惠券金额: {{scope.row.pltCouponAmountFromMt}}</p>
                  <p>商家优惠券金额: {{scope.row.merchantCouponAmount}}</p>
                  <span slot="reference" style="color: #4B7EFE; cursor: pointer">{{scope.row.preferentialAmountMerchants}}</span>
                </el-popover>  
              </template>
          </el-table-column>
          <el-table-column v-else-if="item.slot === 'phone'" :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'>
            <template slot-scope="scope">
              {{scope.row.phone | hidePhoneFourRank}}
            </template>
          </el-table-column>
          <template v-else-if="item.slot === 'verificateStatus'">
            <el-table-column v-if="isShowTabelVerificateStatus" :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'>
              <template slot-scope="scope">
                {{scope.row.verificateStatus}}
              </template>
            </el-table-column>
          </template>
          <el-table-column v-else-if="item.slot === 'action'" :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'> 
            <template slot-scope="scope">
              <el-button-group>
                <el-button type="text" class="default table-btn" size="mini" @click="showDetail(scope.row.orderId)">详情</el-button>
                <template  v-if="scope.row.orderPayFlag === 1">
                  <el-button type="text" class="table-btn" v-if="scope.row.show === 2" size="mini" @click="showRefund(scope.row)">申请退款</el-button>
                  <el-button type="text" class="table-btn" size="mini" @click="showDoc(scope.row.orderId)">补打小票</el-button>
                </template>
                <template v-if="scope.row.orderPayFlag === 4 && [1,3].includes(scope.row.show)">
                  <el-button type="text" :disabled="scope.row.show === 3" size="mini" class="table-btn" @click="confirmRefund('isConfirmRefund', scope.row)">确认退款</el-button>
                  <el-button type="text" :disabled="scope.row.show === 3" size="mini" class="default table-btn"  @click="confirmRefund('isRefuse', scope.row)">拒绝退款</el-button>
                </template>
              </el-button-group>
            </template>
          </el-table-column>
          <el-table-column v-else :label="item.label" :prop="item.prop" :min-width="item.width" :fixed="item.fixed" :key="index" align='center'></el-table-column>
        </template>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageOptions.pageIndex"
          :page-sizes="pageSizes"
          :page-size="pageOptions.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="allTotal">
        </el-pagination>
      </div>
    </el-card>
    <!-- 退款弹窗 -->
    <el-dialog center :visible.sync="isShowDialog">
      <div slot="title">退款原因</div>
      <el-form ref="refund" :rules="refundRules" :model="refundOptions" label-width="90px" size="mini">
        <el-form-item label="退款金额:">
          <div>{{'¥'+refundOptions.amountGun}}</div>
        </el-form-item>
        <el-form-item label="订单编号:">
          <div>{{refundOptions.orderId}}</div>
        </el-form-item>
        <el-form-item label="退款原因:(必选)" prop="refundType">
          <el-select v-model="refundOptions.refundType" size="middle" style="width:420px" placeholder="请选择退款原因">
            <el-option v-for="(item,index) in reasonList" :key="index" :label="item" :value="index"></el-option>
          </el-select>
         </el-form-item>
        <el-form-item prop="remark" >
          <el-input
            type="textarea"
            :rows="7"
            :placeholder="refundOptions.refundType !== '999' ? '请填写退款原因' : '5-200个字，必填 请您补充详细退款原因能够提高退款时效哦~'"
            minlength="5"
            maxlength="200"
            v-model="refundOptions.remark"
            class="text-area"
            style="width:420px"
            @submit.native.prevent>
          </el-input>
        </el-form-item>
      </el-form>   
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDailog(0)">取 消</el-button>
        <el-button type="primary"  @click="closeDailog(1)">确认申请</el-button>
      </div>
    </el-dialog>
    <!-- 订单详情组件 -->
    <orderDetail ref="orderDetail" :orderId="orderId" :isShipStation="isShipStation"></orderDetail>
    <!-- 补打小票提示 -->
    <el-dialog
      top="30vh"
      title="提示"
      :visible.sync="isShowTicket"
      width="30%"
      center>
      <div style="width: 100%;text-align: center">确认补打小票？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowTicket = false">取 消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleTicket">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 确认退款 -->
    <el-dialog
      top="30vh"
      :visible.sync="isConfirmRefund"
      width="400px"
      center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div class="refund-title" slot="title">退款提示</div>
      <div class="refund-des">确定要退款给车主吗？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel-btn" @click="handleRefund(false, 'isConfirmRefund')">取 消</el-button>
        <el-button class="true-btn" @click="handleRefund(true, 'isConfirmRefund')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 拒绝退款 -->
    <el-dialog
      top="30vh"
      :visible.sync="isRefuse"
      width="640px"
      center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div class="refuse-refund-title" slot="title">拒绝退款</div>
      <el-form ref="refuseRefund" :rules="refuseRefundRules" :model="refuseRefundOptions" label-width="91px" size="mini">
        <el-form-item label="退款原因" prop="refuseType">
          <el-select v-model="refuseRefundOptions.refuseType" size="middle" style="width:490px" placeholder="请选择退款原因">
            <el-option v-for="(value,key) in refuseReasonList" :key="key" :label="value" :value="Number(key)"></el-option>
          </el-select>
         </el-form-item>
        <el-form-item prop="refundReason" >
          <el-input
            v-if="refuseRefundOptions.refuseType === 2"
            type="textarea"
            :rows="7"
            placeholder="请描述（必填）"
            maxlength="100"
            v-model="refuseRefundOptions.refundReason"
            class="text-area"
            style="width:490px"
            @submit.native.prevent>
          </el-input>
        </el-form-item>
      </el-form>   
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel-btn" @click="handleRefund(false, 'isRefuse')">取 消</el-button>
        <el-button class="true-btn" @click="handleRefund(true, 'isRefuse')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOrdersByPageNew, submitRefund, makeSmallTicket, exportData, getQueryOrderType, getQueryGasList, getOilNumList, getRefundNum, getSum, confirmRefund, rejectRefund, showRealAmount, getRefundReason } from '@/api/order'
import { exportSearchList } from '@/utils/listTools'
import orderDetail from './orderDetail'
import card from '@/components/work/card'
import addressSelect from '@/components/work/AddressSelect'
import moment from 'moment'
import { mapState } from 'vuex'
import _ from 'lodash'

let tableConfig = [
  {label: '下单时间',prop: 'orderDt',width: 150},
  {label: '支付时间',prop: 'payDt',width: 150},
  {label: '订单号',prop: 'orderId',width: 180},
  {label: '订单来源',prop: 'orderSourceName',width: 101},
  {label: '枪号',prop: 'gunNo',width: 75},
  {label: '油号',prop: 'oilNumName',width: 75},
  {label: '升数',prop: 'litre',width: 75},
  {label: '加油金额（元）',prop: 'amountGun',width: 136},
  {label: '商家优惠金额(元)',prop: 'preferentialAmountMerchants',width: 136, slot: 'preferentialAmountMerchants'},
  // {label: '结算金额(元)',prop: 'settlementAmount',width: 136},
  {label: '用户手机号',prop: 'phone',width: 136, slot: 'phone'},
  {label: '订单状态',prop: 'orderPayFlagName',width: 136},
  {label: '核销状态',prop: 'verificateStatus',width: 136, slot: 'verificateStatus'},
  {label: '所属油站',prop: 'gasName',width: 136},
  {label: '操作' , slot: "action", width: 180, fixed: "right"}
]

const shipTableConfig = {label: '吨数',prop: 'ton',width: 80}
export default {
  name: 'order_orderList', // 订单缓存
  data () {
    return {
      tableConfig,
      shipTableConfig,
      refundNum: 0, // 有退款的订单数
      refuseReasonList: {
        1: '已加油',
        2: '其他'
      }, // 拒绝退款原因列表
      refuseRefundOptions: {}, // （确认、拒绝）退款表单
      isRefuse: false, // 拒绝退款
      isConfirmRefund: false, // 确认退款
      isShowTicket: false,
      orderId: '', // 查看详情使用
      flagsList: { // 订单状态列表
        0: '未支付',
        1: '已支付',
        4: '退款中',
        5: '已退款',
        6: '退款失败',
        7: '已取消'
      }, 
      isShowDialog: false,
      refundOptions: { // 退款选项
        refundType: '',
        amountGun: '',
        orderId: '',
        remark: ''
      },
      reasonList: [],
      isAllLoading: false,
      loading: false,
      exportLoading: false,
      btnLoading: false,
      pageSizes: [20], // 每页展示选项
      orderData: [], // 订单列表
      orderOptions: {
        gasId: '', // 油站id
        orderPayFlag: '', // 订单状态
        phone: '', // 电话号码
        orderId: '', // 订单号
        gunNo: '', // 枪号
        oilNo: '', // 油号
        payDtStart: '', // 支付起始时间
        payDtEnd: '', // 支付终止时间
        orderDtStart: '', // 下单起始时间
        orderDtEnd: '' // 下单终止时间
      },
      pageOptions: {
        pageIndex: 1, // 当前页
        pageSize: 20 // 每页个数
      },
      saveOptions:{},
      allTotal: 0,
      gasList: [], // 油站名称列表
      orderPayFlags: {}, // 订单状态列表
      oilNumList: {}, // 油号列表
      payTime: [], // 支付时间
      checkoutTime: [], //下单时间
      allNumber: {
        allGunAmount: '', // 交易总金额 
        allPayAmount: '', // 实付总金额
        orderTotal: '', // 订单总单数
        allLitre: '', // 升数总和
      },
      address: {
        provinceCode: '',
        cityCode: '',
        countyCode: ''
      },
      showRealAmount: false,
      gasId: '',
      isShipStation: false, // 是否为船舶加油
      pontoonGasIds: [], // 船舶ID的list
      isShowTabelVerificateStatus: false    //表格中是否展示核销状态
    }
  },
  components: {
    orderDetail,
    card,
    addressSelect
  },
  async mounted () {
    this.pontoonGasIds = this.userInfo.pontoonGasIds || []
    this.whetherHasShip()
    this.resetDate()
    this.saveOptions = {...this.orderOptions}
    this.init()
    this.initRefundReason()
    try {
      const {code, result} = await showRealAmount()
      if (code !== 200) return
      this.showRealAmount = result
    } catch (error) {
      console.log(error)
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    refuseRefundRules () {
      return {
        refuseType: [
          { required: true, message: '请选择退款原因', trigger: 'change' }
        ],
        refundReason: [
           { required: this.isOtherRefund, message: '请输入拒绝原因', trigger: 'blur' },
           { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      }
    },
    refundRules () {
      return {
        refundType: [
          { required: true, message: '请选择退款原因', trigger: 'change' }
        ],
        remark: [
           { required: this.isOther, message: '请补充详细退款原因', trigger: 'blur' },
           { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
        ]
      }
    },
    isOther () {
      return this.refundOptions.refundType === '999'
    },
    isOtherRefund () {
      return this.refuseRefundOptions.refuseType === 2
    }
  },
  methods: {
    // 获取需要退款的订单数量
    async getRefundNum () {
      try {
        const { code, result } = await getRefundNum()
        if (code !== 200) return
        this.refundNum = result
      } catch (error) {
        console.log(error.message)
      }
    },
    // 退款弹窗
    beforeClose () {
      this.refundOptions = {
        refundType: '',
        amountGun: '',
        orderId: '',
        remark: ''
      }
      this.isShowDialog = false
    },
    resetDate () {
      this.checkoutTime = [moment().format("YYYY-MM-DD 00:00:00"), moment().format("YYYY-MM-DD HH:mm:ss")]
      this.orderOptions.orderDtStart = moment().format("YYYY-MM-DD 00:00:00")
      this.orderOptions.orderDtEnd = moment().format("YYYY-MM-DD HH:mm:ss")
      this.payTime = []
      this.orderOptions.payDtStart = ''
      this.orderOptions.payDtEnd = ''
    },
    resetForm () {
      this.orderOptions = {
        gasId: '', // 油站id
        orderPayFlag: '', // 订单状态
        phone: '', // 电话号码
        orderId: '', // 订单号
        gunNo: '', // 枪号
        oilNo: '', // 油号
        payDtStart: '', // 支付起始时间
        payDtEnd: '', // 支付终止时间
        orderDtStart: '', // 下单起始时间
        orderDtEnd: '' // 下单终止时间
      },
      this.$refs.address.reset()
      this.resetDate()
      this.pageOptions.pageIndex = 1
      this.pageOptions.pageSize = 20
      this.initContent()
    },
    closeDailog (type) {
      if (type) { // 点击确认
        this.$refs.refund.validate((vaild) => {
          if (vaild) {
            this.submitRefund()
          } else {
            return false
          }
        })
      } else {
        this.refundOptions = {
          refundType: '',
          amountGun: '',
          orderId: '',
          remark: ''
        }
        this.isShowDialog = false
      }
      
    },
    async submitRefund () { // 提交退款信息
      let params = { ...this.refundOptions }
      delete params.amountGun
      try {
        const { code } = await submitRefund(params)
        if (code !== 200) return
        this.$message.success('已成功提交退款信息')
      } catch (error) {
        console.log(error.message)
      } finally {
        this.initContent()
        this.refundOptions = {
          refundType: '',
          amountGun: '',
          orderId: '',
          remark: ''
        }
        this.isShowDialog = false
      } 
    },
    async getSum () { // 获取总数据
      let params = {...this.orderOptions, ...this.pageOptions, ...this.address}
      this.isAllLoading = true
      try {
        const { code, result } = await getSum(params)
        if (code !== 200) return
        this.allNumber = result
      } catch (error) {
        console.log(error.message)
      } finally {
        this.isAllLoading = false
      }
    },
    init () { // 初始化页面
      this.initQueryConditions()
      this.initContent()
    },
    initContent () { // 获取订单数据
      this.getRefundNum()
      this.queryOrderList()
      this.getSum()
    },
    initQueryConditions () { // 获取查询条件
      this.getQueryOrderType()
      this.getQueryGasList()
      this.getOilNumList()
    },
    handleSizeChange (val) {
      console.log(val) // 每页显示多少条改变时触发
    },
    handleCurrentChange (val) {
      this.pageOptions.pageIndex = val
      this.queryOrderList(false, true)
    },
    showDetail (orderId) { // 查看订单详情
      this.orderId = orderId
      this.$refs.orderDetail.isShowDetail = true
    },
    showRefund (item) { // 展示申请退款
      const { amountGun, orderId } = item
      this.refundOptions = {
        amountGun,
        orderId,
        refundType: '',
        remark: ''
       }
      this.isShowDialog = true
    },
    showDoc (orderId) { // 补打小票
      this.orderId = orderId
      this.isShowTicket = true
    },
    async handleTicket () { // 处理补打小票
      try {
        this.btnLoading = true
        const { code } = await makeSmallTicket({
          orderId: this.orderId
        })
        if (code !== 200) return
        this.$message.success('补打小票成功')
      } catch (error) {
        console.log(error.message)
      } finally {
        this.btnLoading = false
        this.isShowTicket = false
        this.initContent()
      }
    },
    query: _.throttle(function (type) { // 点击查询
      let { phone, orderId, gunNo } = this.orderOptions
      if (phone && !(/^1[3456789]\d{9}$/.test(phone))) {
        this.$message.error('请输入正确的手机号')
        return
      }
      if (orderId && !(/^[0-9a-zA-Z]*$/.test(orderId))) {
        this.$message.error('请输入正确的订单号')
        return
      }
      if (gunNo && !(/^[1-9]\d{0,1}$/.test(gunNo))) {
        this.$message.error('请输入正确的油枪号')
        return
      }
      if (type) {
        this.pageOptions.pageIndex = 1
        this.pageOptions.pageSize = 20
      }
      this.queryOrderList(type)
      this.getSum()
    }, 1000),
    async queryOrderList (type, change) { // 获取订单列表
      if (change) {
        this.orderOptions = { ...this.saveOptions }
        // let { payDtStart, payDtEnd } = this.saveOptions
        // this.payTime = [payDtStart, payDtEnd]
        let { orderDtStart, orderDtEnd } = this.saveOptions
        this.checkoutTime = [orderDtStart, orderDtEnd]
      }
      this.loading = true
      let params = {...this.orderOptions, ...this.pageOptions, ...this.address}
      try {
        const { code, result, totalRow } = await getOrdersByPageNew(params)
        if (code !== 200) return
        this.whetherHasShip()
        if (type) this.saveOptions = {...this.orderOptions}
        const { list, isShowVerificateStatus } = result || {}
        this.orderData = list ? list : []
        this.isShowTabelVerificateStatus = isShowVerificateStatus || false   //表格是否展示核销状态
        this.allTotal = totalRow
      } catch (error) {
        console.log(error.message)
      } finally {
        this.loading = false
      }  
    },
    onChangePayTime (val,model,startTime,endTime) {
      if(!val) {
        this.orderOptions[startTime] = ''
        this.orderOptions[endTime] = ''
        this[model] = []
        return
      }
      if((moment(val[1]).valueOf() - moment(val[0]).valueOf()) > 3600 * 1000 * 24 * 59) {
        this.orderOptions[startTime] = ''
        this.orderOptions[endTime] = ''
         this[model] = []
        this.$message.info('选择时间段不能超过60天')
        return
      }
      this.orderOptions[startTime] = val[0]
      this.orderOptions[endTime] = val[1]
    },
    async onExportExcel () {
      let length = this.orderData.length
      if (!length) {
        this.$message.error('导出excel为空，不能导出')
        return
      }
      this.exportLoading = true
      try {
        const { code, result = {} } = await exportData({...this.orderOptions, ...this.address})
        if (code !== 200) return
        // const time = moment().format("YYYY-MM-DD")
        // const name = `订单列表_${time}`
        exportSearchList(result.file, result.fileName)
      } catch (error) {
        console.log(error.message)
      } finally {
        this.exportLoading = false
      }
    },
    async getQueryOrderType () { // 获取订单查询订单状态
      try {
        const { code, result } = await getQueryOrderType()
        if (code !== 200) return
        this.orderPayFlags = result || {}
      } catch (error) {
        console.log(error.message)
      }
    },
    async getQueryGasList () { // 获取订单查询油站信息
      try {
        const { code, result } = await getQueryGasList()
        if (code !== 200) return
        this.gasList = result || []
      } catch (error) {
        console.log(error.message)
      }
    },
    async getOilNumList () { // 获取油号列表
      try {
        const { code, result } = await getOilNumList()
        if (code !== 200) return
        this.oilNumList = result || []
      } catch (error) {
        console.log(error.message)
      }
    },
    // 展示油站退款弹窗
    confirmRefund (type, order) {
      const { gasId, orderId, applySourceType } = order
      this.refuseRefundOptions = {
        ...this.refuseRefundOptions,
        gasId,
        orderId,
        applySourceType
      }
      this[type] = true
    },
    // 处理退款
    handleRefund (type, name) {
      if (!type) {
        this.$message({
          type: 'info',
          message: '已取消'
        })
        this.refuseRefundOptions = {}
        this[name] = false
        return
      } else {
        name === 'isConfirmRefund' ? this.confirmRefundOrder(name) : this.$refs.refuseRefund.validate((vaild) => {
          if (vaild) this.rejectRefundOrder(name)
        })
      }
    },
    // 确认退款
    async confirmRefundOrder (name) {
      const { gasId, orderId, applySourceType } = this.refuseRefundOptions
      const params = {
        gasId,
        orderId,
        applySourceType
      }
      try {
        const { code } = await confirmRefund(params)
        if (code !== 200) return
        this.setOrderType(name)
      } catch (error) {
        console.log(error.message)
      } finally {
        this.setOrderType(name,1)
      }
    },
    // 拒绝退款
    async rejectRefundOrder (name) {
      try {
        const { code } = await rejectRefund(this.refuseRefundOptions)
        if (code !== 200) return
        this.$message.success('操作成功')
      } catch (error) {
        console.log(error.message)
      } finally {
        this.setOrderType(name,1)
      }
    },
    setOrderType (name, type) {
      if (!type) this.$message.success('操作成功')
      this.refuseRefundOptions = {}
      this.resetForm()
      this[name] = false
    },
    // 判断查询油站是否是船舶油站
    whetherHasShip () {
      if (!this.gasId) {
        this.pontoonGasIds.length > 0 ? this.addTableColum() : this.removeTableColum()
        this.isShipStation = this.pontoonGasIds.length > 0
      } else {
        this.pontoonGasIds.includes(this.gasId) ? this.addTableColum() : this.removeTableColum()
        this.isShipStation = this.pontoonGasIds.includes(this.gasId)
      }
    },
    findColumnIndex (key) {
      return this.tableConfig.findIndex(item => item.prop === key)
    },
    addTableColum () {
      if (this.findColumnIndex('ton') !== -1) return

      this.tableConfig.splice(this.findColumnIndex('oilNumName'), 0, this.shipTableConfig)
    },
    removeTableColum () {
      if (this.findColumnIndex('ton') === -1) return

      this.tableConfig.splice(this.findColumnIndex('ton'), 1)
    },
    async initRefundReason () {
      try {
        const { code, result } = await getRefundReason()
        if (code !== 200) return
        this.reasonList = result
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import url('./styles/orderList.less');
.table-btn{
  padding: 2px 5px;
}
</style>
